package tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.List;

import model.Point;
import model.Segment;

public class IOManager {
	private String defaultColour = "black";
	private int iter = 1;
	/**
	 * x;y;label;colour   : points
	 * l1->l2->colour	  : edges
	 */
	public void readInput(String dataFile, List<Point> points, List<Segment> segments) {
		try{
			FileInputStream fstream = new FileInputStream(dataFile);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));

			Debug.println("proceding with reading input");
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				String[] pointsCSV = strLine.split(";");

				// points
				if(pointsCSV.length == 4){
					double x = Double.parseDouble(pointsCSV[0]);
					double y = Double.parseDouble(pointsCSV[1]);
					String label = pointsCSV[2];
					if(label.trim().equals(".")){
						label = "";
					}
					String colour = pointsCSV[3];
					if(colour.trim().equals(".")){
						colour = defaultColour;
					}
					points.add(new Point((int)x,(int)y,colour,label));
				}
				// edges
				else{
					String[] edgesCSV = strLine.split("->");
					if(edgesCSV.length == 3){
						Point v1 = null;
						Point v2 = null;
//
						for(Point v : points){
							if(v.label.equals(edgesCSV[0])){
								v1 = v;
							}
							if(v.label.equals(edgesCSV[1])){
								v2 = v;
							}
						}
						String colour = edgesCSV[2];
						if(colour.trim().equals(".")){
							colour = defaultColour;
						}
						segments.add(new Segment(v1,v2));
					}
				}
			}

			in.close();
		}catch (Exception e){
			Debug.err("Error: " + e.getMessage());
		}
	}
	
	public void saveToFile(List<Point> points, List<Segment> segments){
		String filename = "state" + iter + ".in";
		iter++;
		Debug.println("saving to " + filename);
		try{
			FileWriter fstream = new FileWriter(filename);
			BufferedWriter out = new BufferedWriter(fstream);

			for(Point p: points){
				out.write(p.x+";"+p.y+";" + p.label + ";"+p.colour+"\n");
			}

			for(Segment s: segments){
				if (s.colour == null)
					out.write(s.left.label + "->" + s.right.label + "->" + defaultColour + "\n");
				else
					out.write(s.left.label + "->" + s.right.label + "->" +s.colour+ "\n");
			}
			
			out.close();
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}
		Debug.println("state saved");
	}
}





























